package com.luguokong.pet_rescue.Interceptors;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.luguokong.pet_rescue.util.JwtUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 *   定义请求拦截器
 */

public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 解决因为拦截器先于跨域解决方案处理函数执行，OPTIONS预检请求不携带token而被拦截器抛出错误
        // 拦截器取到请求先进行判断，如果是OPTIONS请求，则放行
        if("OPTIONS".equals(request.getMethod().toUpperCase())) {
            System.out.println("Method:OPTIONS预检请求");
            return true;
        }

        Map<String,Object> map = new HashMap<>();
        // 获取请求头 token
        String token = request.getHeader("token");
        try {
            JwtUtil.validateToken(token); // 验证令牌
            return true; // 放行请求
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            map.put("msg","无效签名！");
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            map.put("msg","token过期！");
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            map.put("msg","token算法不一致！");
        } catch (Exception e) {
            System.out.println("4444----------");
            e.printStackTrace();
            map.put("msg","token无效！");
        }
        map.put("state",false);
        // 将 map 转换为 json
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}
